<template>
  <el-tabs v-model="activeTab" type="card">
    <!-- 员工在线时长tab -->
    <el-tab-pane label="员工在线时长" name="onlineTime">
      <!-- 员工在线时长查询表单 -->
      <el-card class="box-card">
        <div slot="header" style="margin-bottom: 10px;">员工在线时长查询</div>
        <el-form :model="onlineTimeForm" :inline="true">
          <el-form-item label="员工姓名">
            <el-input v-model="onlineTimeForm.name" style="width: 150px;" placeholder="请输入员工姓名" />
          </el-form-item>
          <el-form-item label="员工账号">
            <el-input v-model="onlineTimeForm.account" style="width: 150px;" placeholder="请输入员工账号"/>
          </el-form-item>
          <el-form-item label="登录日期">
            <el-date-picker v-model="onlineTimeForm.date" clearable type="daterange" value-format="YYYY-MM-DD"
              placeholder="选择时间范围" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              style="width: 350px; margin-left: 10px"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getOnlineTimeMessages">查询</el-button>
            <el-button type="info" @click="clearOnlineTimeForm">清空</el-button>
          </el-form-item>
        </el-form>
        <div style="justify-content: space-between;margin-top: 10px;">
          <el-button type="danger" @click="batchDeleteOnlineTimeLogs">批量删除</el-button>
        </div>
      <!-- 员工在线时长信息表格 -->
        <el-table :data="tableData" border style="width: 100%;margin-top: 10px;"
          @selection-change="getOnlineTimeMessagesBySelectedId">
          <el-table-column type="selection" width="40" />
          <el-table-column type="index" label="id" width="50" />
          <el-table-column property="name" label="员工姓名" width="100" />
          <el-table-column property="account" label="员工账号" width="100" />
          <el-table-column property="loginDate" label="登录日期" width="150">
            <template #default="scope">
              {{ moment(scope.row.loginDate).format('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column property="onlineStartTime" label="上线时间" width="180">
            <template #default="scope">
              {{ moment(scope.row.onlineStartTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column property="onlineEndTime" label="下线时间" width="180">
            <template #default="scope">
              {{ moment(scope.row.onlineEndTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column property="totalOnlineTime" label="总在线时长（分钟）" width="160" />
          <el-table-column property="ipAddress" label="登录IP地址" width="130"/>
          <el-table-column label="操作">
            <template #default="scope">
              <el-link type="danger" @click="deleteOnlineTimeLog(scope.row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        </el-card>
        <!-- 员工在线时长分页组件 -->
        <div style="margin-top: 10px;">
          <el-pagination v-model:current-page="currentPageOnlineTime" v-model:page-size="pageSizeOnlineTime"
            :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="totalOnlineTime"
            @size-change="handleSizeChangeOnlineTime" @current-change="handleCurrentChangeOnlineTime" />
        </div>
    </el-tab-pane>
    <!-- 日志tab -->
    <el-tab-pane label="日志" name="log">
      <!-- 日志查询表单 -->
      <el-card class="box-card">
        <div style="margin-bottom: 10px;" slot="header">日志查询</div>
        <el-form :model="logForm" :inline="true">
          <el-form-item label="员工姓名">
            <el-input v-model="logForm.name" style="width: 140px;" placeholder="请输入员工姓名" />
          </el-form-item>
          <el-form-item label="员工账号">
            <el-input v-model="logForm.account" style="width: 140px;" placeholder="请输入员工账号" />
          </el-form-item>
          <el-form-item label="操作时间范围">
            <el-date-picker v-model="logForm.date" clearable type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择时间范围" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              style="width: 350px; margin-left: 10px"></el-date-picker>
          </el-form-item>
          <el-form-item label="操作类型">
            <el-input v-model="logForm.operationType" style="width: 140px;" placeholder="请输入操作类型" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getLogMessages">查询</el-button>
            <el-button type="info" @click="clearLogForm">清空</el-button>
          </el-form-item>
        </el-form>
        <div style="justify-content: sp ace-between;margin-top: 10px;">
          <el-button type="danger" @click="batchDeleteLogs">批量删除</el-button>
        </div>
      <!-- 日志信息表格 -->
        <el-table :data="logTableData" border style="width: 100%;margin-top: 10px;"
          @selection-change="getLogMessagesBySelectedId">
          <el-table-column type="selection" width="150" />
          <el-table-column type="index" label="id" width="150" />
          <el-table-column property="name" label="员工姓名" width="150" />
          <el-table-column property="account" label="员工账号" width="150" />
          <el-table-column property="operationTime" label="操作时间" width="250">
            <template #default="scope">
              {{ moment(scope.row.operationTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column property="operationType" label="操作类型" width="150" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-link type="danger" @click="deleteLog(scope.row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        </el-card>
        <!-- 日志分页组件 -->
        <div style="margin-top: 10px;">
          <el-pagination v-model:current-page="currentPageLog" v-model:page-size="pageSizeLog" :page-sizes="[5, 10, 15, 20]"
            :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="totalLog" @size-change="handleSizeChangeLog" @current-change="handleCurrentChangeLog" />
        </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { ComponentSize, FormInstance } from 'element-plus';
import axios from '@/utils/request';
import moment from 'moment';

// 当前激活的tab
const activeTab = ref('onlineTime');

// 员工在线时长相关设置及数据定义
const size = ref<ComponentSize>('default');
const currentPageOnlineTime = ref(1);
const pageSizeOnlineTime = ref(10);
const disabled = ref(false);
const tableData = ref([]);
const background = ref(true);
const totalOnlineTime = ref(0);
const onlineTimeForm = ref({ name: '',account:'', date: ['', '']});
const onlineTimeMessages = ref([]);
const onlineTimeMessagesId = ref<number[]>([]);

// 获取选中员工在线时长信息id
const getOnlineTimeMessagesBySelectedId = (selectedRows: any) => {
  onlineTimeMessages.value = selectedRows;
  onlineTimeMessagesId.value = [];
  selectedRows.forEach((row) => onlineTimeMessagesId.value.push(row.id));
}

// 清空员工在线时长表单
const clearOnlineTimeForm = () => {
  onlineTimeForm.value.name = '';
  onlineTimeForm.value.account = '';
  onlineTimeForm.value.date = ['', ''];
  getOnlineTimeMessages();
}

// 员工在线时长分页相关逻辑
const refreshOnlineTimeData = () => getOnlineTimeMessages();
const handleSizeChangeOnlineTime = (val: number) => {
  pageSizeOnlineTime.value = val;
  refreshOnlineTimeData();
}
const handleCurrentChangeOnlineTime = (val: number) => {
  currentPageOnlineTime.value = val;
  refreshOnlineTimeData();
}

// 组件挂载时获取初始员工在线时长数据
onMounted(() => {
  getOnlineTimeMessages();
})

// 获取员工在线时长信息
const getOnlineTimeMessages = async () => {
  try {
    const result = await axios.get(`/admin/empOnline?page=${currentPageOnlineTime.value}
    &pageSize=${pageSizeOnlineTime.value}&name=${onlineTimeForm.value.name}&account=${onlineTimeForm.value.account}&startTime=${onlineTimeForm.value.date[0]}&endTime=${onlineTimeForm.value.date[1]}`);
    if (result.data.code === 1) {
      tableData.value = result.data.data.rows;
      totalOnlineTime.value = result.data.data.total;
      if (result.data.data.rows.length === 0) {
        ElMessage.warning('没有查询到相关数据');
      }else if(onlineTimeForm.value.name!==''||onlineTimeForm.value.account!==''||onlineTimeForm.value.date[0]||onlineTimeForm.value.date[1]){
      ElMessage.success('查询成功');
      }
    } else {
      ElMessage.error('获取在线时长信息失败');
    }
  } catch (error: any) {
    console.error('获取在线时长信息时发生错误:', error);
    if (error.response && error.response.status) {
      ElMessage.error(`获取在线时长信息时发生错误，状态码：${error.response.status}，请检查网络或联系后台管理员`);
    } else {
      ElMessage.error('获取在线时长信息时发生网络错误，请检查网络或联系后台管理员');
    }
  }
}

// 批量删除员工在线时长记录
const batchDeleteOnlineTimeLogs = async () => {
  if (onlineTimeMessagesId.value.length === 0) {
  ElMessage.error('请选择要删除的在线时长记录');
  return;
  }
  const isConfirmed = window.confirm('确认要批量删除所选在线时长记录吗？');
  if (!isConfirmed) {
  return;
  }
  try {
    const result = await axios.delete(`/admin/empOnline/${onlineTimeMessagesId.value.join(',')}`);
    if (result.data.code === 1) {
      ElMessage.success('批量删除操作成功');
      getOnlineTimeMessages();
    } else {
      ElMessage.error('批量删除操作失败');
    }
  } catch (error: any) {
    console.error('批量删除操作失败:', error);
    ElMessage.error('批量删除操作失败，请检查网络或联系后台管理员');
  }
}

// 删除单条员工在线时长记录
const deleteOnlineTimeLog = async (id: number) => {
  const isConfirmed = window.confirm('确认要删除该条在线时长记录吗？');
  if (!isConfirmed) {
  return;
  }
  try {
    const result = await axios.delete(`/admin/empOnline/${id}`);
    if (result.data.code == 1) {
      ElMessage.success('删除操作成功');
      getOnlineTimeMessages();
    } else {
      ElMessage.error('删除操作失败');
    }
    } catch (error: any) {
    console.error('删除操作失败:', error)
    ElMessage.error('删除操作失败，请检查网络或联系后台管理员');
    }
}

// 日志相关设置及数据定义
const currentPageLog = ref(1);
const pageSizeLog = ref(10);
const logTableData = ref([]);
const totalLog = ref(0);
const logForm = ref({ name: '', date: ['', ''], operationType: '' ,account:''});
const logMessages = ref([]);
const logMessagesId = ref([]);

// 获取选中日志信息id
const getLogMessagesBySelectedId = (selectedRows: any) => {
  logMessages.value = selectedRows;
  logMessagesId.value = [];
  selectedRows.forEach((row: { id: any; }) => logMessagesId.value.push(row.id));
}

// 清空日志表单
const clearLogForm = () => {
  logForm.value.name = '';
  logForm.value.account = '';
  logForm.value.date = ['', ''];
  logForm.value.operationType = '';
  getLogMessages();
}

// 日志分页相关逻辑
const refreshLogData = () => getLogMessages();
const handleSizeChangeLog = (val: number) => {
  pageSizeLog.value = val;
  refreshLogData();
}
const handleCurrentChangeLog = (val: number) => {
  currentPageLog.value = val;
  refreshLogData();
}

// 组件挂载时获取初始日志数据
onMounted(() => {
  getLogMessages();
})

// 获取日志信息
const getLogMessages = async () => {
  try {
    const result = await axios.get(`/admin/empLog?page=${currentPageLog.value}&pageSize=${pageSizeLog.value}&name=${logForm.value.name}&account=${logForm.value.account}&startTime=${logForm.value.date[0]}&endTime=${logForm.value.date[1]}&operationType=${logForm.value.operationType}`);
    if (result.data.code == 1) {
      logTableData.value = result.data.data.rows;
      totalLog.value = result.data.data.total;
      if (logForm.value.name || logForm.value.operationType || logForm.value.account || logForm.value.date[0] || logForm.value.date[1]) {
        ElMessage.success('查询成功');
      }
    } else {
      ElMessage.error('获取日志信息失败');
    }
    } catch (error: any) {
    console.error('获取日志信息时发生错误:', error);
    if (error.response && error.response.status) {
      ElMessage.error(`获取日志信息时发生错误，状态码：${error.response.status}，请检查网络或联系后台管理员`);
    } else {
      ElMessage.error('获取日志信息时发生网络错误，请检查网络或联系后台管理员');
    }
    }
}

// 批量删除日志
const batchDeleteLogs = async () => {
  if (logMessagesId.value.length == 0) {
  ElMessage.error('请选择要删除的日志');
  return;
  }
  const isConfirmed = window.confirm('确认要批量删除所选日志吗？');
  if (!isConfirmed) {
  return;
  }
  try {
    const result = await axios.delete(`/admin/empLog/${logMessagesId.value.join(',')}`);
    if (result.data.code == 1) {
      ElMessage.success('批量删除操作成功');
      getLogMessages();
    } else {
      ElMessage.error('批量删除操作失败');
    }
    } catch (error: any) {
    console.error('批量删除操作失败:', error)
    ElMessage.error('批量删除操作失败，请检查网络或联系后台管理员');
    }
}

// 删除单条日志
const deleteLog = async (id: any) => {
  const isConfirmed = window.confirm('确认要删除该条日志吗？');
  if (!isConfirmed) {
  return;
  }
  try {
    const result = await axios.delete(`/admin/empLog/${id}`);
    if (result.data.code == 1) {
      ElMessage.success('删除操作成功');
      getLogMessages();
    } else {
      ElMessage.error('删除操作失败');
    }
    } catch (error: any) {
    console.error('删除操作失败:', error)
    ElMessage.error('删除操作失败，请检查网络或联系后台管理员');
    }
}
</script>
